/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fxgreader;

/**
 *
 * Convert an IO stream to a string
 */
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.jdom.Element;

public class HttpUtil {

public static String[] getSIDAndAuth(java.io.InputStream is){
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        try {
            //get first line for SID
            String line = reader.readLine().replaceAll("SID=", "");
            reader.readLine();
            String auth = reader.readLine().replaceAll("Auth=", "");
            return new String[]{line,auth};
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

public static String convertStreamToString(java.io.InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

public static Map parseAtom(java.io.InputStream inputStream) throws IOException, FeedException, ParserException {
    Map rtn = new HashMap();
    ArrayList<Article> artics = new ArrayList<Article>();
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new XmlReader(inputStream));
    System.out.println(feed.getTitle());
    List<SyndEntry> list = feed.getEntries();
    //get gr condistion
    List<Element> foreignMarkups = (List<Element>) feed.getForeignMarkup();
    String gr_continuation = "";
    for (Element foreignMarkup : foreignMarkups) {
        System.out.println(foreignMarkup.getName());
        if (foreignMarkup.getName().equals("continuation")) {
          // extract and populate the value of score
          gr_continuation = foreignMarkup.getValue();
      }
    }
    rtn.put("continuation", gr_continuation);
    System.out.println("gr_continuation : " + gr_continuation);
    Article tmp;
    if (list != null && !list.isEmpty()) {
       System.out.println(list.size());
       for (SyndEntry entry : list) {
        if(entry.getTitle() == null){
            System.out.println("title is null");
            continue;
        }
        String contentStr = "";
        if(entry.getDescription() != null){
            contentStr = entry.getDescription().getValue();

        }else if((entry.getContents() != null) && (entry.getContents().size() != 0)){
                contentStr = ((SyndContent)entry.getContents().get(0)).getValue();
        }else{
            System.out.println("artile("+entry.getTitle()+")'s content is null");
            continue;
        };
//        System.out.println("source : "+entry.getSource());
        tmp = new Article();
        tmp.setTitle(entry.getTitle());
        tmp.setId(entry.getUri());
        tmp.setLink(entry.getLink());
        String regexImg = "<img.+?src\\s*=\\s*['|\"]?\\s*([^'\"\\s>]+).+?/?>?";
        String ImageStr="";
        String ImageSrcStr="";
        Parser parser;
        NodeList nodelist;
        parser = Parser.createParser(contentStr, "utf8");
        NodeFilter textFilter = new NodeClassFilter(TextNode.class);
//        NodeFilter titleFilter = new NodeClassFilter(TitleTag.class);
        OrFilter lastFilter = new OrFilter();
        lastFilter.setPredicates(new NodeFilter[] { textFilter });
        nodelist = parser.parse(lastFilter);
        Node[] nodes = nodelist.toNodeArray();
        String line = "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < nodes.length; i++) {
            Node node = nodes[i];
            if (node instanceof TextNode) {
                TextNode textnode = (TextNode) node;
                line = textnode.getText();
            }else{
                continue;
            }
            if (isTrimEmpty(line))
                continue;
            sb.append(line);
            sb.append(System.getProperty("line.separator"));
        }
        tmp.setBody(sb.toString());
        Pattern p = Pattern.compile(regexImg,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(contentStr);
        while(m.find()){
            ImageSrcStr = m.group(1);
            if(!ImageSrcStr.endsWith(".gif")){
                tmp.addImage(ImageSrcStr);
            }
//            System.out.println(ImageSrcStr);
        }
        artics.add(tmp);
       }
    }
    rtn.put("artics", artics);
    return rtn;
}

public static Map parseHtml(String html) throws ParserException{
        Map rtn = new HashMap();
        Parser parser = Parser.createParser(html, "utf8");
        NodeFilter textFilter = new NodeClassFilter(TextNode.class);
//        NodeFilter titleFilter = new NodeClassFilter(TitleTag.class);
        OrFilter lastFilter = new OrFilter();
        lastFilter.setPredicates(new NodeFilter[] { textFilter });
        NodeList nodelist = parser.parse(lastFilter);
        Node[] nodes = nodelist.toNodeArray();
        String line = "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < nodes.length; i++) {
            Node node = nodes[i];
            if (node instanceof TextNode) {
                TextNode textnode = (TextNode) node;
                line = textnode.getText();
            }
            if (isTrimEmpty(line))
                continue;
            sb.append(line);
            sb.append(System.getProperty("line.separator"));
        }
        rtn.put("content", sb.toString());
        String regexImg = "<img.+?src\\s*=\\s*['|\"]?\\s*([^'\"\\s>]+).+?/?>?";
        String ImageStr="";
        String ImageSrcStr="";
        Pattern p = Pattern.compile(regexImg,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(html);
        ArrayList<String> images = new ArrayList<String>();
        while(m.find()){
            ImageSrcStr = m.group(1);
            if(!ImageSrcStr.endsWith(".gif")){
                images.add(ImageSrcStr);
            }
        }
        rtn.put("images", images);
        return rtn;
}
public static boolean isTrimEmpty(String astr) {
        if ((null == astr) || (astr.length() == 0)) {
            return true;
        }
        if (isBlank(astr.trim())) {
            return true;
        }
        return false;
}
public static boolean isBlank(String astr) {
        if ((null == astr) || (astr.length() == 0)) {
            return true;
        } else {
            return false;
        }
    }
}